<template>
  <el-dialog
    :title="props.goodData.deviceNumber + '货架详情'"
    v-model="visible"
    width="940px"
    @open="handleGoodOpen"
    @close="handleGoodClose"
    append-to-body
    class="good-shelves-dialog"
  >
    <div class="vm-config-channel-dialog-wrapper">
      <div class="channel-basic">
        <span class="vm-row">货架行数：{{ props.goodData.numRows }}</span>
        <span class="vm-col">货架列数：{{ props.goodData.numCols }}</span>
      </div>
      <div class="scroll-container">
        <el-scrollbar ref="scroll" v-loading="listLoading" class="scrollbar" @scroll="updateScrollStatus">
          <div class="shelves-wrapper">
            <div 
              v-for="RowIndex in props.goodData.numRows" 
              :key="RowIndex" 
              class="shelf-row"
            >
              <div 
                v-for="ColIndex in props.goodData.numCols" 
                :key="ColIndex" 
                class="shelf-col"
              >
                <GoodShelvesDialogItem
                  :currentIndex="computedCurrentIndex(RowIndex, ColIndex)"
                  :goodShelves="getShelves(RowIndex,ColIndex)"
                />
              </div>
            </div>
          </div>
        </el-scrollbar>
        <el-icon
          v-if="props.goodData.numCols > 4"
          class="arrow arrow-left"
          :class="scrollStatus === 'LEFT' ? 'disabled' : ''"
          @click="handleClickPrevButton"
          ><ArrowLeft
        /></el-icon>
        <el-icon
          v-if="props.goodData.numCols > 4"
          class="arrow arrow-right"
          :class="scrollStatus === 'RIGHT' ? 'disabled' : ''"
          @click="handleClickNextButton"
          ><ArrowRight
        /></el-icon>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { require } from '@/utils/validate';
const { proxy } = getCurrentInstance();
import {  watch, onMounted, nextTick } from "vue";
import { voListShelves } from "@/api/manage/shelves";
import GoodShelvesDialogItem from "./GoodShelvesDialogItem.vue";
// 滚动插件
import { ElScrollbar } from "element-plus";
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';

// 获取父组件参数
const props = defineProps({
  //  弹层隐藏显示
  goodVisible: {
    type: Boolean,
    default: false,
  },
  //   触发的货道信息
  goodData: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["handleCloseGood"]);
const scrollStatus = ref('LEFT');
const listLoading = ref(false);
const visible = ref(false);
const shelvesList = ref([]);
const scroll = ref(null); //滚动条ref
// 监听货道弹层显示/隐藏
watch(
  () => props.goodVisible,
  (val) => {
    visible.value = val;
  }
);
//获取货架信息
const handleGoodOpen = () => {
  getShelvesList();
};
//通过设备id获取货架信息
// 修复异步操作问题
const getShelvesList = async () => {
  try {
    listLoading.value = true;
    const res = await voListShelves({
      vmId: props.goodData.vmId,
      deviceNumber: props.goodData.deviceNumber
    });
    shelvesList.value = res.rows;
  } finally {
    listLoading.value = false;
  }
};
//通过行列数从shelvesList获取货架信息
// 根据行列数从 shelvesList 获取货架信息
const getShelves = (vmRowIndex, vmColIndex) => {
  const shelfKey = `${vmRowIndex}-${vmColIndex}`;
  return shelvesList.value.find((item) => item.shelfNumber === shelfKey) || {};
};
// 关闭货道弹窗
const handleGoodClose = () => {
  visible.value = false;
  emit("handleCloseGood");
};
//根据行列数获取索引
const computedCurrentIndex = (vmRowIndex, vmColIndex) => {
  return (vmRowIndex - 1) * props.goodData.numCols + vmColIndex-1;
};

// 监听滚动事件，更新滚动状态
onMounted(() => {
  nextTick(() => {
    if (scroll.value) {
      scroll.value.wrapRef.addEventListener('scroll', updateScrollStatus);
    }
  });
});

// 增强滚动状态判断
const updateScrollStatus = () => {
  if (!scroll.value) return;
  
  const { scrollLeft, scrollWidth, clientWidth } = scroll.value.wrapRef;
  scrollStatus.value = scrollLeft <= 0 ? 'LEFT' : 
                      scrollLeft + clientWidth >= scrollWidth ? 'RIGHT' : 'MIDDLE';
};

// 向右滚动按钮
const handleClickNextButton = () => {
  if (!scroll.value) return;
  
  const wrap = scroll.value.wrapRef;
  const scrollStep = wrap.clientWidth * 0.8; // 滚动80%的可见宽度
  
  wrap.scrollTo({
    left: wrap.scrollLeft + scrollStep,
    behavior: 'smooth'
  });
};

// 向左滚动按钮
const handleClickPrevButton = () => {
  if (!scroll.value) return;
  
  const wrap = scroll.value.wrapRef;
  const scrollStep = wrap.clientWidth * 0.8; // 滚动80%的可见宽度
  
  wrap.scrollTo({
    left: wrap.scrollLeft - scrollStep,
    behavior: 'smooth'
  });
};

const colSpan = computed(() => 
  Math.floor(24 / Math.min(props.goodData.numCols, 5))
);
</script>

<style lang="scss" scoped>
@import "../index.scss";

/* 添加货架间距样式 */
.good-shelves-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.vm-config-channel-dialog-wrapper {
  .scrollbar {
    height: 400px;
    
    :deep(.el-scrollbar__wrap) {
      overflow-x: auto;
      overflow-y: auto;
    }
  }
}

.shelves-wrapper {
  padding: 16px;
  display: flex;
  flex-direction: column;
}

.shelf-row {
  display: flex;
  margin-bottom: 20px;
  width: max-content;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.shelf-col {
  width: 160px;
  margin-right: 16px; /* 固定的水平间距 */
  
  &:last-child {
    margin-right: 0;
  }
}

.scroll-container {
  position: relative;
  padding: 0 40px;
  
  .arrow {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 32px;
    background-color: #fff;
    color: #409eff;
    border-radius: 50%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 100;
    
    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }
  
  .arrow-left {
    left: 4px;
  }
  
  .arrow-right {
    right: 4px;
  }
}
</style>